package com.youjiang.meeting.utils.weixin;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * <p>
 * Title: SendRedPack
 * </p> 
 * <p>
 * Description:TODO
 * </p> 
 * <p>
 * Company: YouJiang
 * </p> 
 *
 * @author feng
 * @date 2016年12月5日 下午3:05:51
 * @version 1.0
 */
public class SendRedPack {
	private static String sendurl="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
	/***
	 * 发红包啦
	 * @param req 
	 * @param send_name 商户名称
	 * @param openid 
	 * @param amount 付款金额
	 * @param wishing 红包祝福语
	 * @param act_name 活动名称
	 * @param remark 备注
	 * @return
	 */
	public static Map<String,String> send(HttpServletRequest req,String send_name,String openid,int amount
			,String wishing,String act_name,String remark
			){
		String ip=WeixinSignUtil.getIpAddress(req);
		Map<String,String> map=new HashMap<String,String>();
		map.put("nonce_str", UUID.randomUUID().toString().replace("-", ""));
		map.put("mch_billno", String.valueOf(new Date().getTime()));
		map.put("mch_id", WeixinUtil.MCHID);
		map.put("wxappid", WeixinUtil.APPID);
		map.put("send_name", send_name);
		map.put("re_openid", openid);
		map.put("total_amount", String.valueOf(amount));
		map.put("total_num", String.valueOf(1));
		map.put("wishing", wishing);
		map.put("client_ip", ip);
		map.put("act_name", act_name);
		map.put("remark", remark);
		map.put("scene_id", "PRODUCT_4");
		try {
			String paraMap = WeixinSignUtil.FormatBizQueryParaMap(map);
			paraMap=paraMap+"&key="+WeixinUtil.KEY;
			String sign=WeixinSignUtil.resultMD5(paraMap, true);
			map.put("sign", sign);
			String data=WeixinSignUtil.ArrayToXml(map);
			String result = httpDoPost(data);
			Map<String, String> xmlToMessage = WeixinSignUtil.XMLToMessage(result);
			return xmlToMessage;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static String httpDoPost(String data) throws Exception{
		String result="";
		 KeyStore keyStore  = KeyStore.getInstance("PKCS12");
	        InputStream instream = SendRedPack.class.getResourceAsStream("/apiclient_cert.p12");
	        try {
	            keyStore.load(instream, WeixinUtil.MCHID.toCharArray());
	        } finally {
	            instream.close();
	        }

	        // Trust own CA and all self-signed certs
	        SSLContext sslcontext = SSLContexts.custom()
	                .loadKeyMaterial(keyStore, WeixinUtil.MCHID.toCharArray())
	                .build();
	        // Allow TLSv1 protocol only
	        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
	                sslcontext,
	                new String[] { "TLSv1" },
	                null,
	                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
	        CloseableHttpClient httpclient = HttpClients.custom()
	                .setSSLSocketFactory(sslsf)
	                .build();
	        try {

	            HttpPost httppost = new HttpPost(sendurl);
	            httppost.setEntity(new StringEntity(data,"utf-8"));

	            CloseableHttpResponse response = httpclient.execute(httppost);
	            try {
	                HttpEntity entity = response.getEntity();

	                if (entity != null) {
	                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
	                    String text;
	                    while ((text = bufferedReader.readLine()) != null) {
	                        result=result+text;
	                    }
	                    return result;
	                   // result=text;
	                	//result=EntityUtils.toString(response.getEntity(),"UTF-8");
	                }
	               // EntityUtils.consume(entity);
	            } finally {
	                response.close();
	            }
	        } finally {
	            httpclient.close();
	        }
		return result;
	}
}
